//
//  AppDelegate.m
//  ZJControlsClass
//
//  Created by apple on 2024/10/18.
//

#import "AppDelegate.h"
#import <SangforSDK/SFUemSDK.h>

#import "ViewController.h"

#import "BaseNavgationViewController.h"
#import "BaseTabbarViewController.h"
#import "BaseTabbar.h"
#import "HomeViewController.h"
#import <NTESLiveDetect/NTESLiveDetectManager.h>
#import "PushManager.h"


@interface AppDelegate ()<SFLogoutDelegate, SFAppLaunchDelegate>
@property (nonatomic, strong) SFLaunchInfo *launchInfo;

@end

@implementation AppDelegate

+(instancetype)shareInstance{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    
    /**
     * SDK的初始化模式只能放在didFinishLaunchingWithOptions中
     * 建议配置为SFSDKModeSupportMutable，表示可变授权模式，由服务端指定授权方式。
     * 配置为SFSDKFlagsHostApplication，表示当前集成应用是主应用。
     */
    SFSDKMode mode = SFSDKModeSupportMutable;
    [[SFUemSDK sharedInstance] initSDK:mode
                                 flags:SFSDKFlagsHostApplication
                                 extra:nil];
    
    /**
     * 注册注销事件监听回调，推荐在AppDelegate里面监听,可以做到全局监听，方便统一处理注销事件
     */
    [[SFUemSDK sharedInstance] registerLogoutDelegate:self];
    
    /**
     * 注册拉起回调接口，当被子应用拉起时，会回调onAppLaunched函数
     */
    [[[SFUemSDK sharedInstance] launch] setAppLaunchDelegate:self];
    
//    [[SFUemSDK sharedInstance] startAutoTicket];// 免密登录
    
    
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    NSLog(@"========%@",@([SaUserDataCenter shareIntance].isLogin));
    NSLog(@"========%@",[SaUserDataCenter shareIntance].accessToken);
    
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSLog(@"------%@",[defaults valueForKey:@"accessToken"]);
    
    
    
    if ([[SFUemSDK sharedInstance] startAutoTicket]) {
        // 自动免密情况,不阻塞使用界面,监听认证失败回调
        [self ToTabbar];
    } else {
        BaseNavgationViewController * nav = [[BaseNavgationViewController alloc]initWithRootViewController:[ViewController new]];
        self.window.rootViewController = nav;
        [self.window makeKeyAndVisible];
    }
    
    
    
//    if ([defaults valueForKey:@"isLogin"]) {
//        
////    }
////    if ([SaUserDataCenter shareIntance].isLogin) {
//        [self ToTabbar];
//    }else{
//        BaseNavgationViewController * nav = [[BaseNavgationViewController alloc]initWithRootViewController:[ViewController new]];
//        self.window.rootViewController = nav;
//        [self.window makeKeyAndVisible];
//    }
    
    
    [self iqKeyBoardsHOWOrhide];
    
    // 注册推送
    [[PushManager shared] registerRemoteNotification];
    
//    [JPUSHService setupWithOption:launchOptions appKey:@"ecbb02341b4a56f91c0b82ac"
//                           channel:@"channel"
//                 apsForProduction:NO
//            advertisingIdentifier:nil];
//    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
//    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
//    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//      // 可以添加自定义 categories
//      // NSSet<UNNotificationCategory *> *categories for iOS10 or later
//      // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
//    }
//    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
//    
//    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
//        NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);
//    }];
//    
    return YES;
}

-(void)ToTabbar{
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    BaseNavgationViewController * nav = [[BaseNavgationViewController alloc]initWithRootViewController:[BaseTabbarViewController new]];
    [self.window setRootViewController:nav];
    [self.window makeKeyAndVisible];
    
//    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
//    self.window.rootViewController = [[BaseNavgationViewController alloc]initWithRootViewController:[BaseTabbarViewController new]];
//    [self.window makeKeyAndVisible];
    
    
    
//    UIViewController *vc;
//    if (![SaUserDataCenter shareIntance].isLogin){
//        vc = [[BaseNavgationViewController alloc] initWithRootViewController:[HomeViewController new]];
//    }else{
//        vc = [BaseTabbarViewController new];
        
//    }
//    self.window.rootViewController = vc;
//    self.window.rootViewController = [[BaseNavgationViewController alloc]initWithRootViewController:[BaseTabbarViewController new]];
//    BaseNavgationViewController * nav = [[BaseNavgationViewController alloc]initWithRootViewController:[HomeViewController new]];
//    [self.window setRootViewController:nav];
//    [self.window makeKeyAndVisible];
    
    
    
}

// 处理键盘
-(void)iqKeyBoardsHOWOrhide{
    

}

#pragma mark - SFAppLaunchDelegate 主从回调
- (void)onAppLaunched:(SFLaunchInfo *)launchInfo {
    self.launchInfo = launchInfo;
    NSLog(@"Appdelegate onAppLaunched:%@", launchInfo);
    
    // 外部拉起当前应用分享日志, extraData有分享日志的信息，集成侧可以处理此事件
    if (launchInfo.launchReason == SFLaunchReasonAppUploadLog) {
        return;
    }
    
    //如果当前未认证，则退出此流程，等待认证成功后再跳回子应用
    if ([[SFUemSDK sharedInstance].auth getAuthStatus] != SFAuthStatusAuthOk) {
        NSLog(@"Appdelegate onAppLaunched: not auth ok");
        [LUtilityTools showAlertWithTitle:@"当前未认证" message:@"请认证通过后再调用跳回子应用" buttonAction:^{
            
        }];
        
        
        
        //TODO 如果需要优化体验,可以当前主应用没有认证，可以暂存拉起信息，比如self.launchInfo,等到认证成功之后再通过此信息跳回子应用
        return;
    }
    
    //当前主应用是已认证状态，可以直接拉起子应用
    [self showAuthorizationAlert];
}

- (void)showAuthorizationAlert {
    /**
     * 检查子应用是否有被发布到控制台，如果检测失���，需要提醒管理员将子应用发布给此用户，这个接口判断也是为了优化体验，目的是能及时发现管理员配置错误。
     */
    if ([[SFUemSDK sharedInstance].launch checkAppAuthorized:self.launchInfo.srcAppBundleId]) {
        NSString *subAppName = self.launchInfo.srcAppName;
        NSString *mainAppName = @"ZJControlsClass";
        NSString *message = [NSString stringWithFormat:@"“%@”申请获取“%@”的网关登录信息，是否同意？", subAppName, mainAppName];;
        //这里给个弹窗提醒用户要不要同意拉起子应用，目的是为了优化体验与安全性，您也可以不加弹窗，直接调用launchApp接口拉回子应用
        [LUtilityTools showAlertWithTitle:@"温馨提示" message:message cancelTitle:@"拒绝" buttonAction:^{
            // 拒绝
            self.launchInfo = nil;
        } sureTitle:@"同意" ButtonAction:^{
            /**
             * 拉起子应用进行授权登录认证
             */
            [[SFUemSDK sharedInstance].launch launchApp:self.launchInfo.srcAppBundleId reason:SFLaunchReasonSubappAuthBack extraData:@"用户自定义数据" completeHandler:nil];
            self.launchInfo = nil;
        }];
        
        
        
    } else {
        [LUtilityTools showAlertWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"无应用“%@”的使用权限，请联系管理员发布此应用", self.launchInfo.srcAppName] buttonAction:^{
            
        }];
        self.launchInfo = nil;
    }
}

#pragma mark - SFLogoutDelegate 注销回调
- (void)onLogout:(SFLogoutType)type message:(nonnull BaseMessage *)msg
{
    NSString *reason = @"";
    switch (type) {
        case SFLogoutTypeUser:
            reason = @"用户注销";
            break;
        case SFLogoutTypeTicketAuthError:
            reason = @"免密失败";
            break;
        case SFLogoutTypeServerShutdown:
            reason = @"服务端注销";
            break;
        case SFLogoutTypeAuthorError:
            reason = @"授权失败";
            break;
        default:
            reason = @"未知";
            break;
    }
    
    //注销以后需要重新认证才能使用VPN和沙箱能力，此时根据您自己的需求可以给出提示或者跳转到登陆页面，此Demo的做法是提示并跳到首页，让用户可以重新登录
//    [AlertUtil showAlert:@"注销" message:[NSString stringWithFormat:@"注销原因 : %@ code:<%ld> desc<%@>", reason, msg.errCode, msg.errStr]  completion:^{
//        [self goBackToRootViewController];
//    }];
    [LUtilityTools showAlertWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"注销原因 : %@ code:<%ld> desc<%@>", reason, msg.errCode, msg.errStr] buttonAction:^{
        [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
    }];
    
    
    
}

// 注册远程推送成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [[PushManager shared] handleDeviceToken:deviceToken];

}

// 注册远程推送失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    [[PushManager shared] handleRegisterForRemoteNotificationsWithError:error];
}




@end
